package src.jdbc2;

import java.sql.*;

//封装方法
public class jdbcStudy3 {
    private static  String url="jdbc:mysql://localhost:3306/stu?useSSL=false&serverTimezone=UTC";
    private  static  String username="root";
    private  static  String passWord="";

    public jdbcStudy3() {
    }

    public static Connection conn() throws ClassNotFoundException, SQLException {

        //注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //使用api连接数据库
        Connection connection = DriverManager.getConnection(url,username,passWord);
        return connection;
    }
    public  static int objectALL(Connection connection,String sql) throws SQLException {
        Statement statement = connection.createStatement();
        int i = statement.executeUpdate(sql);
        return i;
    }

    //数据的增加
    /*
    "insert into tbl_lixue values('ooo','8888',null )";
     */
    public void insertAll() throws SQLException, ClassNotFoundException {
        Connection conn = jdbcStudy3.conn();
        String sql="insert into tbl_lixue values('ooo','8888',null )";
        int i = jdbcStudy3.objectALL(conn,sql);
        System.out.println(i);
    }

    //数据的删除
    //"delete from t_user where id=6";
    public void deletData() throws SQLException, ClassNotFoundException {
        Connection conn = jdbcStudy3.conn();
        String sql="delete from tbl_lixue where id=6";
        int i = jdbcStudy3.objectALL(conn, sql);
        System.out.println(i);
    }

    //数据的更新
    public void updateDate() throws SQLException, ClassNotFoundException {
        Connection conn = jdbcStudy3.conn();
        String sql= "update tbl_lixue set username='aa99' where id=5";
        int i = jdbcStudy3.objectALL(conn, sql);
        System.out.println(i);
    }
    //数据的查询
    public void findALL() throws SQLException, ClassNotFoundException {
        Connection conn = jdbcStudy3.conn();
        String sql= " select * from tbl_lixue";
        Statement statement = conn.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
        while(resultSet.next()){
            int id = resultSet.getInt("id");
            String username = resultSet.getString("username");
            String password = resultSet.getString("password");
            System.out.println(id+"|"+username+"|"+password);
        }
        statement.close();
        conn.close();
    }
}
